package com.jxx.controller;

import com.jxx.pojo.*;
import com.jxx.service.UserSecurityService;
import com.jxx.service.UserService;
import com.jxx.util.UserThreadLocal;
import com.jxx.vo.ChangePassword;
import com.jxx.vo.SysResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;

@RestController
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserSecurityService userSecurityService;

    /**
     * @author LKS
     * @desc 门户端登录
     * @param userAccount,userPassword
     * @return SysResult
     * @data 2020年11月18日23:14:40
     */
    @RequestMapping("login")
    public SysResult login(String userAccount,String userPassword) {
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(userAccount, userPassword);
        try {
            if (userAccount.isEmpty()){
                return SysResult.fail("用户名不能为空");
            }else if (userPassword.isEmpty()){
                return SysResult.fail("请输入密码!!");
            }else {
                subject.login(token);//执行登录方法,如果没有异常就说明ok了
                User user = UserThreadLocal.get();
                Session session = subject.getSession();
                user.setUserPassword("********");
                user.setSalt("********");
                session.setAttribute("user", user);
                return SysResult.success();
            }
        } catch (UnknownAccountException e){//用户名不存在
            return SysResult.fail("账号不存在");
        } catch(IncorrectCredentialsException e) {//密码错误
            return SysResult.fail("密码错误");
        }
    }

    /**
     * @author LKS
     * @desc 门户端用户回显
     * @param request
     * @return SysResult
     * @data 2020年11月18日23:14:40
     */
    @RequestMapping("showName")
    public User showName(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            return null;
        }
        return user;
    }

    /**
     * @author LKS
     * @desc 门户端登出
     * @param request
     * @return SysResult
     * @data 2020年11月18日23:14:40
     */
    @RequestMapping("logout")
    public ModelAndView logout(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        if (user==null){
            return null;
        }else {
            Enumeration em = request.getSession().getAttributeNames();
            while(em.hasMoreElements()){
                request.getSession().removeAttribute(em.nextElement().toString());
            }
            ModelAndView  modelAndView= new ModelAndView("redirect:/");
            return modelAndView ;
        }
    }

    /**
     * @author LKS
     * @desc 门户端用户注册
     * @param cfgPassword
     * @return SysResult
     * @data 2020年11月18日23:14:40
     */
    @RequestMapping("register")
    public SysResult register(String userAccount, String userPassword,String cfgPassword){
        return userService.register(userAccount,userPassword,cfgPassword);
    }

    /**
     * @author LKS
     * @desc 门户端用户注册，用户信息校验
     * @param userAccount,type,callback
     * @return SysResult
     * @data 2020年11月18日23:14:40
     */
    @RequestMapping("check/{userAccount}/{type}")
    public SysResult checkUser(@PathVariable String userAccount, @PathVariable Integer type){
        //只需要校验数据库中是否有结果
        boolean flag = userService.checkUser(userAccount,type);
        if (flag==true){
            return SysResult.fail("用户名已存在");
        }
        return SysResult.success().setMsg("");
    }

    /**
     * @author LKS
     * @desc 展示门户端密保问题
     * @param   userId
     * @return List<UserSecurity>
     * @date 2020年12月7日19:21:26
     */
    @RequestMapping("showSecurityQuestion")
    public List<UserSecurity> showSecurityQuestion(Integer userId){
        return userSecurityService.showSecurityQuestion(userId);
    }

    /**
     * @author LKS
     * @desc 修改密码
     * @param   changePassword,request
     * @return SysResult
     * @date 2020年12月7日19:21:51
     */
    @RequestMapping("changePassword")
    public SysResult changePassword(@RequestBody ChangePassword changePassword, HttpServletRequest request){
        return userSecurityService.changePassword(changePassword,request);
    }


    /**
    * @Description: 增加收货地址
    * @Param: [address]
    * @return: com.jxx.vo.SysResult
    * @Author: laixinghua
    * @Date: 2020/11/24 0024 上午 8:46
    */
    @RequestMapping("address/insertaddress")
    public SysResult insertaddress(@RequestBody Address address){
        int userId=1;//先设个假数据，后面从登陆的信息拿
        address.setUserId(userId);
        int i=userService.insertaddress(address);
        return SysResult.success();
    }
    /**
    * @Description: 根据用户id查找收货地址
    * @Param: [userId]
    * @return: com.jxx.vo.SysResult
    * @Author: laixinghua
    * @Date: 2020/11/24 0024 上午 9:27
    */
    @RequestMapping("address/findaddressByUserId")
    public SysResult findaddressByUserId(){
        Integer userId=1;//先设个假数据，后面从登陆的信息拿
        List<Address> addresses = userService.findaddressByUserId(userId);
        return SysResult.success(addresses);
    }
    /**
     * @Description: 根据地址id删除地址
     * @Param: [addressId]
     * @return: int
     * @Author: laixinghua
     * @Date: 2020/11/24 0024 下午 8:27
     */
    @RequestMapping("address/deleteAddressByaddressId/{addressId}")
    public SysResult deleteAddressByaddressId(@PathVariable Integer addressId) {
        int i = userService.deleteAddressByaddressId(addressId);
        return SysResult.success();
    }
    /**
    * @Description: 根据地址id查找收货地址
    * @Param: [addressId]
    * @return: com.jxx.vo.SysResult
    * @Author: laixinghua
    * @Date: 2020/11/26 0026 下午 2:09
    */
    @RequestMapping("address/findaddressByaddressId/{addressId}")
    public SysResult findaddressByaddressId(@PathVariable Integer addressId) {
        Address address = userService.findaddressByaddressId(addressId);
        return SysResult.success(address);
    }
    /**
     * @Description: 根据地址id更改收货地址
     * @Param: [addressId]
     * @return: int
     * @Author: laixinghua
     * @Date: 2020/11/26 0026 下午 6:45
     */
    @RequestMapping("address/updateAddressByaddressId")
    public SysResult updateAddressByaddressId(@RequestBody Address address) {
        int i = userService.updateAddressByaddressId(address);
        return SysResult.success();
    }
    /**
    * @Description: 更改密码
    * @Param: [password]
    * @return: com.jxx.vo.SysResult
    * @Author: laixinghua
    * @Date: 2020/11/28 0028 下午 2:44
    */
    @RequestMapping("updatePassword")
    public SysResult updatePassword(@RequestBody Password password) {
        Integer userId=1;//TODO：先设个假数据，后面从登陆的信息拿
        String userPassword=userService.findPasswordByUserId(userId);
        //todo:密码要加盐值再加密才能比较，存储
        if(userPassword.equals(password.getUserPassword())){
            String newPassword=password.getNewpassword();
            int i=userService.updatePassword(newPassword,userId);
            if(i>0){
                //todo:调用退出用户操作
                return SysResult.success();

            }
            return SysResult.fail("增加失败");
        }
            else {
            return SysResult.fail("密码错误");
        }

    }
    /**
    * @Description: 根据用户ID找用户信息
    * @Param: [userId]
    * @return: com.jxx.vo.SysResult
    * @Author: laixinghua
    * @Date: 2020/12/7 0007 下午 7:49
    */
    @RequestMapping("findUserInfoByUserId")
    public SysResult findUserInfoByUserId(Integer userId) {
        userId=1;
        UserInfo userInfo =userService.findUserInfoByUserId(userId);
        return SysResult.success(userInfo);
    }
    /**
    * @Description: 根据用户Id增加用户信息
    * @Param: [userInfo]
    * @return: SysResult
    * @Author: laixinghua
    * @Date: 2020/12/8 0008 上午 9:50
    */
    @RequestMapping("insertUserInfo")
    public SysResult insertUserInfo(@RequestBody UserInfo userInfo) {
        int userId=1;
        userInfo.setUserId(userId);
        int insert = userService.insertUserInfo(userInfo);
        return SysResult.success();
    }

    /**
    * @Description: 根据用户Id更改用户信息
    * @Param: [userInfo]
    * @return: SysResult
    * @Author: laixinghua
    * @Date: 2020/12/8 0008 上午 9:50
    */
    @RequestMapping("UpdateUserInfo")
    public SysResult UpdateUserInfo(@RequestBody UserInfo userInfo) {
        int userId=1;
        userInfo.setUserId(userId);
        int i = userService.UpdateUserInfo(userInfo);
        return SysResult.success();
    }
}
